import functools
import math
import uuid

from flask import Blueprint, render_template, request, jsonify, g, session, redirect
from sqlalchemy import and_, or_

from models import db, AdminInfo, UserInfo, CovInfo
from datetime import timedelta, datetime

cov = Blueprint("cov", __name__, url_prefix='/cov')  # 实例化一个蓝图Blueprint对象


# 装饰器验证用户登录
def required_login(view_fun):
    @functools.wraps(view_fun)
    def fun1(*args, **kwargs):
        if 'username' not in session:
            return redirect('/tologin')
        g.User = UserInfo.query.get(session['id_card'])
        return view_fun(*args, **kwargs)

    return fun1


@cov.route('/write', methods=['GET'])
@required_login
def writePage():
    id_card = session.get('id_card')
    username = session.get('username')
    phone = session.get('phone')
    cov = CovInfo.query.filter_by(phone=phone).first()
    return render_template("write.html", username=username,
                           id_card=id_card, phone=phone, cov=cov)


@cov.route('/covWrite', methods=['POST'])
@required_login
def covWrite():
    covobj = CovInfo()
    covobj.id = uuid.uuid1()
    covobj.name = request.values.get("name")
    covobj.phone = request.values.get("phone")
    covobj.temperature = request.values.get("temperature")
    covobj.currentProvince = request.values.get("currentProvince")
    covobj.currentCity = request.values.get("currentCity")
    covobj.currentCounty = request.values.get("currentCounty")
    covobj.currentDetail = request.values.get("currentDetail")
    covobj.is_fever_cough_1 = request.values.get("is_fever_cough_1")
    covobj.is_fever_cough_2 = request.values.get("is_fever_cough_2")
    covobj.is_fever_cough_3 = request.values.get("is_fever_cough_3")
    covobj.is_fever_cough_0 = request.values.get("is_fever_cough_0")
    covobj.is_covid = request.values.get("is_covid")
    covobj.is_infection = request.values.get("is_infection")
    covobj.area_level = request.values.get("area_level")
    covobj.is_health_code = request.values.get("is_health_code")
    covobj.is_back_foreign = request.values.get("is_back_foreign")
    covobj.is_touch_foreigner = request.values.get("is_touch_foreigner")
    covobj.description = request.values.get("description")
    db.session.add(covobj)
    db.session.commit()
    return jsonify(result=200)


@cov.route('/covUpdate', methods=['POST'])
def covUpdate():
    # 判断是否传入了id来决定是更新还是添加
    id = request.values.get('id')

    cov = CovInfo.query.filter_by(id=id).first()
    cov.name = request.values.get("name")
    cov.phone = request.values.get("phone")
    cov.temperature = request.values.get("temperature")
    cov.currentProvince = request.values.get("currentProvince")
    cov.currentCity = request.values.get("currentCity")
    cov.currentCounty = request.values.get("currentCounty")
    cov.currentDetail = request.values.get("currentDetail")
    cov.is_fever_cough_1 = request.values.get("is_fever_cough_1")
    cov.is_fever_cough_2 = request.values.get("is_fever_cough_2")
    cov.is_fever_cough_3 = request.values.get("is_fever_cough_3")
    cov.is_fever_cough_0 = request.values.get("is_fever_cough_0")
    cov.is_covid = request.values.get("is_covid")
    cov.is_infection = request.values.get("is_infection")
    cov.area_level = request.values.get("area_level")
    cov.is_health_code = request.values.get("is_health_code")
    cov.is_back_foreign = request.values.get("is_back_foreign")
    cov.is_touch_foreigner = request.values.get("is_touch_foreigner")
    cov.description = request.values.get("description")
    db.session.commit()
    return jsonify(result=200)


@cov.route("/list", methods=['GET'])
def covlist():
    return render_template("cov-index.html")


@cov.route('/query', methods=['GET'])
def query():
    # 获取page参数 默认为1
    page = int(request.args.get('page', 1))
    # 获取每页显示数据条数默认为2
    per_page = int(request.args.get('perpage', 15))

    name = request.values.get("name")
    phone = request.values.get("phone")
    if name is None:
        name = ''
    if phone is None:
        phone = ''

    filter_list = []
    # 从数据库查询数据
    if name is not None or phone is not None:
        if name:
            filter_list.append(CovInfo.name.like('%' + name + '%'))
        if phone:
            filter_list.append(CovInfo.phone == phone)
        paginates = CovInfo.query.filter(*filter_list).order_by(
            'create_time').paginate(page, per_page, error_out=False)
    else:
        paginates = CovInfo.query.order_by(
            'create_time').paginate(page, per_page, error_out=False)

    stus = paginates.items
    # totalpage为总页面数
    totalpage = math.ceil(paginates.total / per_page)
    return render_template("cov-index.html", paginate=paginates, stus=stus, totalpage=totalpage,
                           name=name,
                           phone=phone)
